package com.abhinav.xml.parser.sax;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserApp {

	public static void main(String argv[]) {
		SAXParserApp saxParserApp = new SAXParserApp();
		saxParserApp.parseDocument();
	}

	public void parseDocument() {
		try {
			SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
			
			DefaultHandler handler = new CustomSAXHandler();
			// File xmlFile = new File("catalog.xml");
			InputStream xmlFile = SAXParserApp.class.getResourceAsStream("/com/abhinav/xml/catalog.xml");
			
			saxParser.parse(xmlFile, handler);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private class CustomSAXHandler extends DefaultHandler {
		public CustomSAXHandler() {}

		public void startDocument() throws SAXException {
			System.out.println("Event Type: Start Document");
		}

		public void endDocument() throws SAXException {
			System.out.println("Event Type: End Document");
		}

		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			System.out.println("**** "+uri+"\t"+localName);
			System.out.println("Event Type: Start Element");
			System.out.println("\t Element Name:" + qName);
			for (int i = 0; i < attributes.getLength(); i++) {
				System.out.print("\t Attribute Name:" + attributes.getQName(i));
				System.out.print("\t Attribute Value:" + attributes.getValue(i) + "\n");
			}

		}

		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			System.out.println("Event Type: End Element");
		}

		public void characters(char[] ch, int start, int length)
				throws SAXException {
			System.out.println("Event Type:  Text");
			String str = (new String(ch, start, length));
			System.out.println(str);
		}

		public void error(SAXParseException e) throws SAXException {
			System.err.println("Error: " + e.getMessage());
		}

		public void fatalError(SAXParseException e) throws SAXException {
			System.err.println("Fatal Error: " + e.getMessage());
		}

		public void warning(SAXParseException e) throws SAXException {
			System.err.println("Warning: " + e.getMessage());
		}
	}

}
